#!/bin/bash

# timeout seconds
HUNG_THRESHOLD=5

killflag=false

if [ "$1" == "-k" ]; then
    killflag=true
fi

virsh list --state-running |grep "^[[:space:]]*[0-9][0-9]*"|awk '{print $1" "$2}'|while read id inst;do
    read pid vmuuid <<< $(ps -ef |grep $inst |grep qemu |sed -e \
's/^[a-z0-9]\+[[:space:]]\+\([0-9]\+\)[[:space:]]\+\(.*\) -uuid \([0-9a-f-]\+\).*/\1 \3/')
    echo "$inst id: $id uuid: $vmuuid"
    timeout $HUNG_THRESHOLD virsh domstats $id >/dev/null
    if [ $? -eq 124 ]; then # timeout
        if $killflag; then
            echo "kill $inst $vmuuid on $(hostname)"
            kill -9 $pid
        else
            echo "$inst $vmuuid on $(hostname) hung" 
        fi
    fi
done

